package filter;

import java.util.HashMap;

import pub.fjf.http.HttpRequest;
import pub.fjf.http.HttpRequestFilter;
import pub.fjf.http.HttpResponse;
import pub.fjf.tools.Json;
import pub.fjf.tools.StringTools;

public class HostProxy extends HttpRequestFilter{
	private String selfHost="";
	private HashMap<String,String> hostMap=new HashMap<String,String>();
	private boolean checkRegister(String url, HttpRequest httpRequest, HttpResponse httpResponse) {
		boolean result=false;
		String rest=StringTools.dropPrefixString(url, "/@ProxyRegister");
		if(rest!=null) {
			String proxyHost=httpRequest.getParameter();
			if(proxyHost!=null&&proxyHost.length()>0) {
				StringBuffer proxyLocation=new StringBuffer();
				proxyLocation.append(httpRequest.getClient());
				proxyLocation.append(httpRequest.getBody());
				this.hostMap.put(proxyHost, proxyLocation.toString());
				httpResponse.sendData("OK", "text/txt");
				System.out.println("Add HostProxy: proxyHost = \""+proxyHost+"\" proxyLocation = \""+proxyLocation+"\"");
				result=true;
			}
		}
		return result;
	}
	private boolean checkProxy(String url, HttpRequest httpRequest, HttpResponse httpResponse) {
		boolean result=false;
		String host=httpRequest.getValue("Host");
		if(host!=null) {
			int index=host.indexOf(this.selfHost);
			if(index>0&&host.charAt(index-1)=='.') {
				String proxyHost=host.substring(0, index-1);
				String proxyLocation=this.hostMap.get(proxyHost);
				if(proxyLocation!=null) {
					httpResponse.sendNewLocation(proxyLocation+url);
					result=true;
				}
			}
		}
		return result;
	}
	@Override
	public boolean handleHttpRequest(String url, HttpRequest httpRequest, HttpResponse httpResponse) {
		// TODO Auto-generated method stub
		boolean result=false;
		if(!result) {
			result=this.checkProxy(url, httpRequest, httpResponse);
		}
		if(!result) {
			result=this.checkRegister(url, httpRequest, httpResponse);
		}
		return result;
	}

	@Override
	public void config(Json jsonVar) {
		// TODO Auto-generated method stub
		if(jsonVar.getTypeCode()==Json.TYPE_OBJECT) {
			Json selfHost=jsonVar.getMember("selfHost");
			if(selfHost.getTypeCode()==Json.TYPE_OBJECT) {
				this.selfHost=selfHost.getValueString();
			}
		}
	}

}
